<template>
    <div class="use-next-layout group/body">
        <BaHeader/>
        <div class="account">
            <div class="account__container">
                <div class="account__container__left">
                    <div class="login-container">
                        <div class="register-box__title">现在注册，即可免费体验</div>
                        <div class="register-box__sub-title">全渠道开店拓客，轻松实现裂变营销</div>
                        <el-form class="zent-form zent-form--horizontal" data-cp-zv="2.3.0"
                                 ref="registerRef"
                                 @keyup.enter="onRegisterSubmit(registerRef)"
                                 :rules="registerRules"
                                 :model="state.register">
                            <div class="account-input">
                                <div class="zent-select-v2 zent-select-v2-s account-input__select" data-zv="v10.0.11"><span class="zent-select-v2-text" data-zv="v10.0.11" title="中国 +86">中国 +86</span><i class="zenticon zenticon-down" data-zv="v10.0.11"></i></div>
                                <div class="zent-input-wrapper zent-input--size-normal account-input__input"
                                     data-zv="v10.0.11">
                                    <input placeholder="请输入手机号"
                                           maxlength="11"
                                           type="text"
                                           class="zent-input"
                                           data-zv="v10.0.11"
                                           v-model="state.register.mobile"
                                    />
                                </div>
                                <p class="account-input__warning">验证完成后，可使用该手机号登录或找回密码</p>
                            </div>
                            <div class="account-password" v-if="state.actionType == 'password'">
                                <div class="zent-input-wrapper zent-input--size-normal account-password__input account-password__input--show-forget"
                                     data-zv="v10.0.11">
                                    <input name="captcha" type="text"    v-model="state.register.captcha" placeholder="输入验证码"
                                           class="zent-input" data-zv="v10.0.11" >
                                </div>
                                <el-button link
                                    size="large"
                                    @click="sendRegisterCaptchaPre"
                                    :loading="state.sendCaptchaLoading"
                                    :disabled="state.codeSendCountdown <= 0 ? false : true"
                                           class="account-password__forget-password"
                                >
                                    {{
                                        state.codeSendCountdown <= 0
                                            ? t('register.Send')
                                            : state.codeSendCountdown + t('register.Seconds')
                                    }}
                                </el-button>
                                <p class="account-password__error"></p>
                            </div>
                            <div class="login-container__auto">

                                <div>
                                    <label class="zent-checkbox-wrap login-container__protocol__check shake-motion"
                                           data-zv="v10.0.11">
                                        <span class="zent-checkbox" data-zv="v10.0.11">
                                            <span class="zent-checkbox-inner" data-zv="v10.0.11"></span>
                                            <input type="checkbox" data-zv="v10.0.11"/>
                                        </span>
                                        <div class="zent-checkbox-label" data-zv="v10.0.11">
                                            阅读并同意
                                            <a target="_blank" rel="noopener noreferrer"
                                               href="/examples/agreement">用户协议</a>
                                            <span>、</span>
                                            <a target="_blank" rel="noopener noreferrer"
                                               href="/examples/statement">隐私声明</a>
                                        </div>
                                    </label>
                                </div>
                                <div>
                                    <el-button
                                        @click="onRegisterSubmit(registerRef)"
                                        :loading="state.loading.register"
                                        round
                                        style="width: 100%;"
                                        type="primary"
                                        size="large"
                                        class="form-btn zent-btn-primary zent-btn-large zent-btn-block zent-btn-border-transparent zent-btn login-container__btn js-login-verify-code-btn clickable-button-disabled "
                                    >
                                        注&nbsp;册
                                    </el-button>
                                </div>
                                <div class="login-container__links">
                                    <div class="login-container__links__actions">
                                        已有账号，<a class="js-goto-register-btn" href="/login">去登录</a>
                                    </div>
                                </div>
                            </div>
                        </el-form>
                    </div>
                </div>
                <a class="account__container__right" href="/" target="_blank" rel="noopener noreferrer">
                    <img class="account__container__right__cover" src="https://iph.href.lu/380x520" alt=""
                         loading="lazy"/>
                </a>
            </div>
        </div>
        <BaFooter/>
    </div>
</template>
<script setup lang="ts">
import type {FormItemRule, FormInstance} from 'element-plus'
import {sendEms, sendSms} from '~/api/common'
import {checkIn, retrievePassword} from '~/api/user/index'
import LoginFooterMixin from '~/composables/mixins/loginFooter.vue'
import clickCaptcha from '~/composables/clickCaptcha'
import {useI18n} from 'vue-i18n'

const {t} = useI18n()
let timer: NodeJS.Timeout
useSeoMeta({
    title: '用户登录',
})

interface State {
    tab: 'mobileLogin' | 'captchaLogin' | 'passwordLogin' | 'Register'
    actionType: 'mobile' | 'captcha' | 'password'
    loading: {
        login: boolean
        register: boolean
        retrievePassword: boolean
    }
    login: {
        username: string
        password: string
        captchaInfo: string
        captchaId: string
        smscode:string
        keep: boolean
    }
    register: {
        registerType: 'email' | 'mobile'
        username: string
        password: string
        mobile: string
        email: string
        captcha: string
    }
    retrieveDialogWidth: number
    showRetrievePasswordDialog: boolean
    accountVerificationType: string[]
    retrievePasswordForm: {
        type: 'email' | 'mobile'
        account: string
        captcha: string
        password: string
    }
    sendCaptchaLoading: boolean
    codeSendCountdown: number
    to: string
}
const passType=ref(false)
const showPass=()=>{
    passType.value=!passType.value
}
const route = useRoute()
const userInfo = useUserInfo()
const siteConfig = useSiteConfig()
const memberCenter = useMemberCenter()
const loginRef = ref<FormInstance>()
const registerRef = ref<FormInstance>()
const retrieveRef = ref<FormInstance>()
const state: State = reactive({
    tab: 'captchaLogin',
    actionType: 'password',
    loading: {
        login: false,
        register: false,
        retrievePassword: false,
    },
    login: {
        username: '18888888888',
        password: 'admin123',
        smscode:'',
        captchaInfo: '',
        captchaId: uuid(),
        keep: false,
    },
    register: {
        registerType: 'mobile',
        username: '',
        password: '',
        mobile: '',
        email: '',
        captcha: '',
    },
    retrieveDialogWidth: 36,
    showRetrievePasswordDialog: false,
    accountVerificationType: [],
    retrievePasswordForm: {
        type: 'email',
        account: '',
        captcha: '',
        password: '',
    },
    sendCaptchaLoading: false,
    codeSendCountdown: 0,
    to: route.query.to as string,
})

const loginRules: Partial<Record<string, FormItemRule[]>> = reactive({
    username: [buildValidatorData({name: 'required', title: t('login.login.User name')})],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.login.Password')
    }), buildValidatorData({name: 'password'})],
})
const switchLoginType = (loginType: any) => {
    state.actionType = loginType
    state.register.mobile = ''
    state.register.email = ''
}
const registerRules: Partial<Record<string, FormItemRule[]>> = reactive({
    username: [
        buildValidatorData({name: 'required', title: t('login.login.User name')}),
        buildValidatorData({name: 'account', title: t('login.login.User name')}),
    ],
    email: [
        buildValidatorData({name: 'required', title: t('login.login.Email')}),
        buildValidatorData({name: 'email', title: t('login.login.Email')}),
    ],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.login.Password')
    }), buildValidatorData({name: 'password'})],
    mobile: [buildValidatorData({
        name: 'required',
        title: t('login.login.Mobile')
    }), buildValidatorData({name: 'mobile'})],
    captcha: [buildValidatorData({name: 'required', title: t('login.login.Captcha')})],
})

const retrieveRules: Partial<Record<string, FormItemRule[]>> = reactive({
    account: [buildValidatorData({name: 'required', title: t('login.login.Account name')})],
    captcha: [buildValidatorData({name: 'required', title: t('login.login.Captcha')})],
    password: [buildValidatorData({
        name: 'required',
        title: t('login.login.Password')
    }), buildValidatorData({name: 'password'})],
})

const onLoginSubmitPre = () => {
    loginRef.value?.validate((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => onLoginSubmit(captchaInfo))
    })
}
const onLoginSubmit = (captchaInfo: string) => {
    state.loading.login = true
    state.login.captchaInfo = captchaInfo
    checkIn('post', {...state.login, tab: state.tab.toLocaleLowerCase()})
        .then((res) => {
            if (res.code != 1) return
            userInfo.dataFill(res.data.userInfo)
            if (state.to) return (location.href = state.to)
            navigateTo({path: res.data.routePath})
        })
        .finally(() => {
            state.loading.login = false
        })
}

const switchTab = (type: State['tab']) => {
    state.tab = type
    if (type == 'Login') {
        loginRef.value?.resetFields()
        loginRef.value?.clearValidate()
    } else {
        registerRef.value?.resetFields()
        registerRef.value?.clearValidate()
    }
}

const sendRegisterCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    registerRef.value?.validateField([state.register.registerType, 'username', 'password']).then((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => sendRegisterCaptcha(captchaInfo))
    })
}
const sendRegisterCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.register.registerType == 'email' ? sendEms : sendSms
    func(state.register[state.register.registerType], 'user_register', {
        captchaInfo,
        captchaId: state.login.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const sendRetrieveCaptchaPre = () => {
    if (state.codeSendCountdown > 0) return
    retrieveRef.value?.validateField('account').then((valid) => {
        if (!valid) return
        clickCaptcha(state.login.captchaId, (captchaInfo: string) => sendRetrieveCaptcha(captchaInfo))
    })
}
const sendRetrieveCaptcha = (captchaInfo: string) => {
    state.sendCaptchaLoading = true
    const func = state.retrievePasswordForm.type == 'email' ? sendEms : sendSms
    func(state.retrievePasswordForm.account, 'user_retrieve_pwd', {
        captchaInfo,
        captchaId: state.login.captchaId,
    })
        .then((res) => {
            if (res.code == 1) startTiming(60)
        })
        .finally(() => {
            state.sendCaptchaLoading = false
        })
}

const onRegisterSubmit = (registerRef: FormInstance | undefined = undefined) => {
    if (!registerRef) return
    registerRef.validate((valid) => {
        if (!valid) return
        state.loading.register = true
        checkIn('post', {...state.register, tab: state.tab.toLocaleLowerCase()})
            .then((res) => {
                if (res.code != 1) return
                userInfo.dataFill(res.data.userInfo)
                navigateTo({path: res.data.routePath})
            })
            .finally(() => {
                state.loading.register = false
            })
    })
}

const onSubmitRetrieve = (retrieveRef: FormInstance | undefined = undefined) => {
    if (!retrieveRef) return
    retrieveRef.validate((valid) => {
        if (valid) {
            state.loading.retrievePassword = true
            retrievePassword({...state.retrievePasswordForm})
                .then((res) => {
                    if (res.code == 1) {
                        state.showRetrievePasswordDialog = false
                        endTiming()
                        onResetForm(retrieveRef)
                    }
                })
                .finally(() => {
                    state.loading.retrievePassword = false
                })
        }
    })
}

const startTiming = (seconds: number) => {
    state.codeSendCountdown = seconds
    timer = setInterval(() => {
        state.codeSendCountdown--
        if (state.codeSendCountdown <= 0) {
            endTiming()
        }
    }, 1000)
}
const endTiming = () => {
    state.codeSendCountdown = 0
    clearInterval(timer)
}

const dialogSize = () => {
    if (import.meta.server) return
    let clientWidth = document.documentElement.clientWidth
    let width = 36
    if (clientWidth <= 790) {
        width = 92
    } else if (clientWidth <= 910) {
        width = 56
    } else if (clientWidth <= 1260) {
        width = 46
    }
    state.retrieveDialogWidth = width
}

checkIn('get').then((res) => {
    if (res.code != 1) return
    state.accountVerificationType = res.data.accountVerificationType
    state.retrievePasswordForm.type = res.data.accountVerificationType.length > 0 ? res.data.accountVerificationType[0] : ''
})

onMounted(() => {
    dialogSize()
    useEventListener(window, 'resize', dialogSize)
    if (route.query.type == 'register') state.tab = 'Register'
})
onUnmounted(() => {
    endTiming()
})
</script>
<style scoped>
@import url('https://b.yzcdn.cn/wsc-pc-account/login_b97b5429.css');
.register-box__title {
    font-weight: 500;
    font-size: 26px;
    color: #323233;
}
.register-box__sub-title {
    font-size: 16px;
    color: #969799;
    line-height: 24px;
    margin-top: 6px;
}
.account-password__forget-password{
    padding-left: 0;
}
.account-input__warning{
    bottom:-34px;
}
</style>
